import json
import os
import random
import time

from selenium import webdriver
from selenium.webdriver import ChromeOptions

def cookie_exist(func):
    def wrapper( *args, **kwargs):
        cookies = json.load(open('cookies.json', 'rb')) if os.path.isfile('cookies.json') else []
        if not cookies:
            url = "https://www.zhipin.com"
            # options = ChromeOptions()
            # options.add_argument('headless')
            driver = webdriver.Chrome()
            driver.get(url)
            driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument",
                                   {
                                       "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"""})
            input("请先手动登录, 完成后按回车继续")

            cookies = driver.get_cookies()
            with open('cookies.json', 'wb') as f:
                f.write(json.dumps(cookies).encode('utf-8'))
            print("获取cookie成功！")
        return func( *args, **kwargs)
    return wrapper
@cookie_exist
def get_cookie_str():
    with open("cookies.json","rb") as f:
        cookies=json.load(f)
    cookie_str = ""
    for cookie in cookies:
        str = cookie["name"] + "=" + cookie["value"] + "; "
        cookie_str += str
    # print(cookie_str)
    return cookie_str
# @cookie_exist
# def get_uuid():
#     with open("cookies.json","rb") as f:
#         cookies=json.load(f)
#     for cookie in cookies:
#         if cookie["name"]=="uuid":
#             uuid=cookie["value"]
#             return uuid
# @cookie_exist
# def get_userId():
#     with open("cookies.json", "rb") as f:
#         cookies = json.load(f)
#     for cookie in cookies:
#         if cookie["name"] == "u":
#             userId = cookie["value"]
#             return userId
@cookie_exist
def get_cookies():
    with open("cookies.json","rb") as f:
        cookies=json.load(f)
    cookies_dic={}
    for cookie in cookies:
        cookies_dic[cookie["name"]]=cookie["value"]
    return cookies_dic